// manager/pages/ftp/index.js
import { request } from '../../../utils/request';
// import util from '../../../common/util';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        activeIndex: 0,
        tabList: [
            {
				id: 1,
				sts: 0,
                text: "FTP计算器"
            },
            {
				id: 2,
				sts: 1,
                text: "支行行长查询"
            },
            {
				id: 3,
				sts: 2,
                text: "客户经理查询"
            }
        ],
        // 日期限制
        // startDate: "",
        form: {
            beginDate: "",
            endDate: "",
            ftpBusinessVariety: 1,
            businessAmount: "",
            interestRateType: 2,
            customerRate: "",
            repricingFrequencyType: 12,
            loanRepaymentModeType: 2,
            repaymentFrequencyType: 1,
            interestFrequencyType: 1,
        },

        ftpResult: null,
        // 业务品种
        busiList: [],
        // 利率类型
        rateTypeList: [],
        // 重定价频率
        repriFreList: [],
        // 还款方式
        repMethList: [],
        // 还款频率
        repayFreList: [],
        // 结息频率
        InterSetFreList: [],
        showResult: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // this.setData({
        //     startDate: util.getDateByNumber(0),
        // })
        this.initValidate();
        this.getDictionaryInfo();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })
    },

    /**
     * 选择框变化时
     */
    pickerChagne(e){
        let { key, value } = e.detail;
        let { form } = this.data;
        form[key] = value;
        this.setData({
            form
        })
    },

    /**
     * 日期选择
     */
    bindDateChange: function(e) {
        let { key } = e.currentTarget.dataset;
        this.setData({
            ['form.'+key]: e.detail.value
        })
        if(this.data.form.beginDate&&this.data.form.endDate){
            
            // 固定利率
            if(this.data.form.interestRateType == 1){
                this.compareDateSize(this.data.form.beginDate,this.data.form.endDate,1)
            }
            // 浮动利率
            if(this.data.form.interestRateType == 2){
                this.compareDateSize(this.data.form.beginDate,this.data.form.endDate,90)
            }
        }
    },

    /**
     * 获取字典
     */
    getDictionaryInfo() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
                dictType: "ftp_business_variety"
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    busiList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "interest_rate_type"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    rateTypeList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "repricing_frequency_type"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    repriFreList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "loan_repayment_mode_type"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    repMethList: res.data
                })
            }
            return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "repayment_frequency_type"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    repayFreList: res.data
                })
            }return request({
                url: "/commonApi/getDictionaryInfo",
                method: "GET",
                data: {
                    dictType: "interest_frequency_type"
                }
            })
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    InterSetFreList: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    tabChange(e){
        let { index } = e.detail;
        this.setData({
            activeIndex: index
        })
    },

    showFtpResult(e){
        this.setData({
            showResult: true
        })
    },
    
    close(e){
        this.setData({
            showResult: false
        })
    },

    // 获取指定日期的前n天(传负值)和后n天(传正值)的日期
    // getDateByNumber(dateStr,n) {
    //     dateStr = dateStr.replace("-","/");
    //     var date = new Date(dateStr);
    //     var year = date.getFullYear();
    //     var month = date.getMonth() + 1;
    //     var day = date.getDate();
    //     if(day <= n) {
    //         if(month > 1) {
    //             month = month - 1;
    //         } else {
    //             year = year - 1;
    //             month = 12;
    //         }
    //     }
    //     date.setDate(date.getDate() + n);
    //     year = date.getFullYear();
    //     month = date.getMonth() + 1;
    //     day = date.getDate();
    //     return `${[year, month, day].map(this.formatNumber).join('-')}`;
    // },
    // formatNumber(n) {
    //     n = n.toString()
    //     return n[1] ? n : `0${n}`
    // },

    compareDateSize(start,end,n){
        start = start.replace("-","/");
        end = end.replace("-","/");
        var startDate = new Date(start).getTime();
        var endDate = new Date(end).getTime();
        console.log(startDate,endDate)
        if((endDate - (24 * 60 * 60 * 1000) * n) < startDate){
            wx.showToast({
                title: `业务到期日要大于业务起始日${n}天`,
                icon: 'none',
                duration: 2000
            })
            return false
        }else{
            return true
        }
    },


    // 保存
    save(e) {
        if(this.data.form.beginDate&&this.data.form.endDate){
            // 固定利率
            if(this.data.form.interestRateType == 1){
                if(!this.compareDateSize(this.data.form.beginDate,this.data.form.endDate,1)){
                    return
                }
            }
            // 浮动利率
            if(this.data.form.interestRateType == 2){
                if(!this.compareDateSize(this.data.form.beginDate,this.data.form.endDate,90)){
                    return
                }
            }
        }
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        request({
            url: `/ftp/calculate`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '测算成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                this.setData({
                    ftpResult:res.data,
                    showResult: true
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            beginDate: {
                required: true
            },
            endDate: {
                required: true
            },
            ftpBusinessVariety: {
                required: true
            },
            businessAmount: {
                required: true,
                jxs: true,
            },
            interestRateType: {
                required: true
            },
            customerRate: {
                required: true,
                dxs: true,
            },
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            beginDate: {
                required: '请选择业务起始日'
            },
            endDate: {
                required: '请选择业务到期日'
            },
            ftpBusinessVariety: {
                required: '请选择业务品种'
            },
            businessAmount: {
                required: '请输入业务金额',
            },
            interestRateType: {
                required: '请选择营销成果'
            },
            customerRate: {
                required: '请输入对客利率',
            },
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)

        // 自定义验证规则
        this.WxValidate.addMethod('jxs', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '业务金额为大于0数字或保留2位的小数')
        // 自定义验证规则
        this.WxValidate.addMethod('dxs', (value, param) => {
            var returnVal = true;
            if(/^\d+(\.\d{0,2})?$/.test(value)&&value>0){
                returnVal = true;
            }else{
                returnVal = false;
                return false
            }
            return this.WxValidate.optional(value) || returnVal
        }, '对客利率为大于0数字或保留2位的小数')
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})